package com.xone.xapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.xone.xapp.SlideSwitch.OnSwitchChangedListener;

public class AutoCompleteActivity extends BasicActivity {
	protected String TAG = AutoCompleteActivity.class.getSimpleName();
	protected AutoCompleteTextView autoCompleteTextView;
	protected AutoCompleteListAdapter adapter;
	protected String saleType;
	protected InitDataTask initDataTask;
	protected String autoRequestUrl;
	protected Bundle bundle;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		bundle = this.getIntent().getExtras();
		if (null != bundle) {
			saleType = bundle.getString("saleType");
			if (StringUtils.isBlank(saleType)) {
				Toast.makeText(this, "无产品类型信息", Toast.LENGTH_SHORT).show();
				this.finish();
				return;
			}
		}
		super.onCreate(savedInstanceState);
		if (!ContextUtils.isOnline(this)) {
			Toast.makeText(this, "请检查网络连接", Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		TextView optTypeView = (TextView)findViewById(R.id.auto_product);
		autoRequestUrl = "/product/listAutoJsonItems.html";
		if ("0".equals(saleType)) {
			optTypeView.setText("产品发布");
		} else if ("1".equals(saleType)) {
			optTypeView.setText("促销发布");
		} else if ("2".equals(saleType)) {
			optTypeView.setText("组团发布");
		} else if ("3".equals(saleType)) {
			optTypeView.setText("求购发布");
			autoRequestUrl = "/purchase/listAutoJsonItems.html";
		}
		autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
		findViewById(R.id.btnSearch).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				passParameters();
			}
		});
		adapter = new AutoCompleteListAdapter(this, saleType);
		adapter.initWithJsonList(null);
		autoCompleteTextView.setAdapter(adapter);
		autoCompleteTextView.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() < 2) {
					return;
				}
				if (null != initDataTask) {
					initDataTask.cancel(true);
				}
				initDataTask = new InitDataTask(getContext(), autoCompleteTextView, adapter);
				initDataTask.execute(s.toString());
			}
		});
		autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				TextView text = (TextView)arg1;
				System.out.println("搜索的文本:" + text.getText());
				autoCompleteTextView.setText(text.getText());
			}
		});
		findViewById(R.id.calc_clear_txt_Prise).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				autoCompleteTextView.setText("");
			}
		});
		initStatus();
		clickCheck();
		findViewById(R.id.product_create_zone).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(AutoCompleteActivity.this, ProductCreateActivity.class);
				if ("3".equals(saleType)) {
					i = new Intent(AutoCompleteActivity.this, PurchaseCreateActivity.class);
				}
				i.putExtra("saleType", saleType);
				startActivity(i);
			}
		});
	}
	
	/**
	 * 点击开关控件时的检查
	 */
	protected void clickCheck() {
		String [] sample = new String [] {
				"_1", "0", "1", "2", "3", "4"
		};
		String [] keys = new String [] {
				"productType", "productLocation", "credit"
		};
		for (String key : keys) {
			for (String si: sample) {
				String tag = key + si;
				int identify = getContext().getResources().getIdentifier(tag, "id", getContext().getPackageName());
				if (identify != 0) {
					SlideSwitch sSwitch = (SlideSwitch)findViewById(identify);
					sSwitch.setTag(tag);
					sSwitch.setOnSwitchChangedListener(new OnSwitchChangedListener() {
						@Override
						public void onSwitchChanged(SlideSwitch ts, int status) {
							String mTag = (String)ts.getTag();
							if (mTag.endsWith("_1")) {
								mTag = mTag.replaceFirst("_1$", "");
								String [] ms = new String [] {"0", "1", "2", "3", "4"
								};
								for (String tms : ms) {
									int mid = getContext().getResources().getIdentifier(mTag + tms, "id", getContext().getPackageName());
									if (mid != 0) {
										slideSwitchCheck(mid, !ts.getStatus());
									}
								}
							} else {
								mTag = mTag.replaceFirst("\\d+$", "");
								String [] ms = new String [] {"0", "1", "2", "3", "4"
								};
								//需要判断四个全部开启和部分开启时,不限关闭，全部关闭时，不限开启
								boolean result = true;
								for (String cms : ms) {
									int mid = getContext().getResources().getIdentifier(mTag + cms, "id", getContext().getPackageName());
									if (mid != 0) {
										SlideSwitch sSwitch = (SlideSwitch)findViewById(mid);
										result = result && !sSwitch.getStatus();
									}
								}
								int mid = getContext().getResources().getIdentifier(mTag + "_1", "id", getContext().getPackageName());
								if (mid != 0) {
									slideSwitchCheck(mid, result);
								}
							}
						}
					});
				}
			}
		}
	}
	
	/**
	 * 设置开关控件的状态
	 * @param id
	 * @param status
	 */
	protected void slideSwitchCheck(int id, boolean status) {
		SlideSwitch sSwitch = (SlideSwitch)findViewById(id);
		sSwitch.setStatus(status);
	}
	
	/**
	 * 初始化界面上的控件默认值
	 */
	protected void initStatus() {
		String keywords = bundle.getString("keywords");
		if (StringUtils.isNotBlank(keywords)) {
			autoCompleteTextView.setText(keywords);
		}
		String [] keys = null;
		if ("3".equals(saleType)) {
			keys = new String [] {
					"purchaseType", "purchaseLocation", "credit"
			};
		} else {
			keys = new String [] {
					"productType", "productLocation", "credit"
			};
		}
		for (String key : keys) {
			String kon = bundle.getString(key);
			if (StringUtils.isNotBlank(kon)) {
				String [] svalue = kon.split(",");
				for (String skey : svalue) {
					int identify = getContext().getResources().getIdentifier(key.replaceFirst("purchase", "product") + skey, "id", getContext().getPackageName());
					if (identify != 0) {
						SlideSwitch sSwitch = (SlideSwitch)findViewById(identify);
						sSwitch.setStatus(true);
					}
				}
			} else {
				//不限选中
				int identify = getContext().getResources().getIdentifier(key.replaceFirst("purchase", "product") + "_1", "id", getContext().getPackageName());
				if (identify != 0) {
					SlideSwitch sSwitch = (SlideSwitch)findViewById(identify);
					sSwitch.setStatus(true);
				}
			}
		}
	}
	
	/**
	 * 把请求的参数传入到上一个activity中去
	 */
	protected void passParameters() {
		Intent data = new Intent();
		data.putExtra("keywords", autoCompleteTextView.getText().toString());
		String [] sample = new String [] {
				"_1", "0", "1", "2", "3", "4"
		};
		String [] keys = null;
		if ("3".equals(saleType)) {
			keys = new String [] {
					"purchaseType", "purchaseLocation", "credit"
			};
		} else {
			keys = new String [] {
					"productType", "productLocation", "credit"
			};
		}
		for (String key : keys) {
			StringBuffer sb = new StringBuffer();
			for (String s : sample) {
				int identify = getContext().getResources().getIdentifier(key.replaceFirst("purchase", "product") + s, "id", getContext().getPackageName());
				if (identify != 0) {
					SlideSwitch ss = (SlideSwitch)findViewById(identify);
					if (ss.getStatus()) {
						sb.append(s);
						sb.append(",");
					}
				}
			}
			String dataType = sb.toString().replaceFirst(",$", "");
			if (dataType.endsWith("_1")) {
				dataType = "";
			} else {
				dataType = dataType.replaceFirst("_1,", "");
			}
			data.putExtra(key, dataType);
		}
		setResult(0, data);
		finish();
	}
	public String getSaleType() {
		return saleType;
	}
	public void setSaleType(String saleType) {
		this.saleType = saleType;
	}
	@Override
	public boolean isLoginCheck() {
		return false;
	}
	public boolean onCreateOptionMenu(Menu menu) {
		return true;
	}
	@Override
	public String getHeaderTitle() {
		return "更多操作";
	}
	@Override
	public int getContentView() {
		return R.layout.auto_complete_main;
	}
	/**
	 * 取向导的图片默认图片
	 * @author hunnyhu
	 */
	public class InitDataTask extends AsyncTask<String, Integer, List<JSONObject>> {
		protected Context context;
		protected AutoCompleteTextView autoCompleteTextView;
		protected AutoCompleteListAdapter adapter;
		public InitDataTask(Context context, AutoCompleteTextView autoCompleteTextView, AutoCompleteListAdapter adapter) {
			this.context = context;
			this.autoCompleteTextView = autoCompleteTextView;
			this.adapter = adapter;
		}
		@Override
		protected List<JSONObject> doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}
			List<NameValuePair> reqparams = new ArrayList<NameValuePair>();
			if ("3".equals(saleType)) {
				reqparams.add(new BasicNameValuePair("purchase.purchaseName", params[0]));
			} else {
				reqparams.add(new BasicNameValuePair("product.saleType", saleType));
				reqparams.add(new BasicNameValuePair("product.productName", params[0]));
			}
			return HttpUtils.httpGet(Constants.APP_URL + autoRequestUrl, reqparams, 
				new HttpUtils.onGetSuccessListener<List<JSONObject>>() {
					@Override
					public List<JSONObject> onSuccess(int status, String result) {
						if (HttpUtils.SC_OK == status) {
							return JSONUtils.getJSONListFromIdentifyString(result, "list");
						}
						return null;
					}
				});
		}
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			super.onPostExecute(result);
			if (null != result && !result.isEmpty()) {
				adapter.initWithJsonList(result);
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	protected void onResume() {
		super.onResume();
	}
}
